package com.dailyblue.java.project.community.controller;

import com.dailyblue.java.project.community.service.CommunityService;
import com.dailyblue.project.estate.commons.bean.Community;
import com.dailyblue.project.estate.commons.util.DateUtil;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.UUID;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/community")
public class CommunityController {
    @Resource
    private CommunityService service;
    @Value("${images.upload.community.path}")
    private String imagePath;

    @GetMapping
    public JsonResult find() {
        return service.find();
    }

    @SneakyThrows
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file) {
        log.info("开始长传图片");
        String dateFormat = DateUtil.getNowDate();
        String path = imagePath + dateFormat;
        String name1 = file.getOriginalFilename();
        String type = name1.substring(name1.lastIndexOf('.'));
        String newName = UUID.randomUUID().toString() + type;
        File uploadFile = new File(path, newName);
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        log.info("文件名：{},地址是：{}", newName, path);
        file.transferTo(uploadFile);
        return ResultTool.success(uploadFile.getAbsolutePath());
    }

    @PostMapping("/save")
    public JsonResult save(Community community) {
        log.info("community:{}", community);
        String code = UUID.randomUUID().toString();
        code = code.substring(0, code.indexOf('-'));
        community.setCode(code);
        String sqlFilePath = community.getThumbnail();
        int index = sqlFilePath.indexOf("images");
        sqlFilePath = sqlFilePath.substring(index);
        community.setThumbnail(sqlFilePath);
        return service.saveCommunity(community);
    }

    @GetMapping("/search")
    public JsonResult search(String begin, String end, String code) {
        return service.searchCreateTime(begin, end, code);
    }
}
